#include "NFile.h"
#include "NLogger.h"
#include "NCoreException.h"

//stl
#include <stdio.h>
#include <sstream>
#include <strstream>


using namespace Core;

NFile::NFile()
	:mFileInputStream(NULL),
	 mFileOutputStream(NULL)
{
}

NFile::~NFile(void)
{
	Close();
}

Mode NFile::GetMode() const
{
	return mFileMode;
}

FILE* NFile::GetFile()
{
	return &mFile;
}

bool NFile::Open(const char* file, Mode mode)
{
	mFileMode = mode;

	switch (mode)
	{
	case Mode_Read:
		mFileInputStream = new std::ifstream(file,std::ifstream::binary);
		break;
	case Mode_Write:
		mFileOutputStream = new std::ofstream(file,std::ofstream::binary);
		break;
	case Mode_Append:
		throw NCoreException("NFile::Open::Case-Mode_Append - NOT IMPLEMENTED!");
		break;
	default:
		return false;
		break;
	}
	return true;
}

void NFile::Close()
{
	if(mFileInputStream)
	{
		mFileInputStream->close();
		delete(mFileInputStream);
		mFileInputStream = NULL;
	}

	if(mFileOutputStream)
	{
		delete(mFileOutputStream);
		mFileOutputStream = NULL;
	}
}

void NFile::Write(const char* value, unsigned int size)
{
	if(mFileOutputStream != NULL)
	{
		//write header saying how long the next write it
		std::stringstream sStream;
		sStream << size;
		mFileOutputStream->write(sStream.str().c_str(), sFileHeader_Size);

		char msgbuf[100];
		sprintf_s(msgbuf, "Serialization::Write value = %s with size = %i \n", value,  size);
		OutputDebugString(msgbuf);

		//write string
		mFileOutputStream->write(value, size);
	}
}